<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\MoneyLog;
use app\common\model\Packages;
use app\common\model\UserPackagesConfig;
use fast\Random;
use think\Config;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }



    /**
     * 会员中心
     */
    public function index()
    {
        $userInfo['order_num']      = $this->auth->order_num;
        $userInfo['agency_num']     = $this->auth->agency_num;
        $userInfo['withdraw_money'] = $this->auth->withdraw_money;
        $userInfo['money']          = $this->auth->money;
        $userInfo['nickname']       = $this->auth->nickname;
        $userInfo['mobile']         = $this->auth->mobile;
        $userInfo['avatar']         = $this->auth->avatar;
        $userInfo['truthname']      = $this->auth->truthname;
        $userInfo['zfb_account']    = $this->auth->zfb_account;
        $userInfo['parent_id']      = $this->auth->parent_id;
        $userInfo['wx']             = $this->auth->wx;
        $userInfo['id']             = $this->auth->id;
        $userInfo['zhi_money']      = MoneyLog::where(['user_id'=>$this->auth->id,'memo'=>'直推奖励'])->sum('money');
        $userInfo['team_money']     = MoneyLog::where(['user_id'=>$this->auth->id,'memo'=>'代理推广奖励'])->sum('money');
        $this->success('', ['userinfo'=>$userInfo,'spread'=>config('site.spread')]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
//        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
//            $this->error(__('Captcha is incorrect'));
//        }

        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username        = $this->request->post('username');
        $password        = $this->request->post('password');
        $towpassword     = $this->request->post('towpassword');
        $mobile          = $this->request->post('mobile');
        $invitation_code = $this->request->post('invitation_code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($password != $towpassword) {
            $this->error(__('两次密码不一致'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $extend['invitation_code'] = Random::alnum(8);
        $extend['type']            = 1;
        if ($invitation_code) {

            $UserInfo = \app\common\model\User::where(['invitation_code' => $invitation_code])->find();
            if (!$UserInfo) {
                $this->error('邀请人不存在');
            }
            if($UserInfo['three_id']){
                $this->error(__('添加的下级作单，下级没有佣金'));
            }
            $extend['parent_id'] = $UserInfo['id'];
            $extend['two_id']    = $UserInfo['parent_id'];
            $extend['three_id']  = $UserInfo['two_id'];
        }
        $ret = $this->auth->register($username, $password, '', $mobile, $extend);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 添加代理
     */
    public function addagency(){
        $username       = $this->request->post('username');
        $nickname       = $this->request->post('nickname');
        $password       = $this->request->post('password');
        $wx             = $this->request->post('wx');
        $mobile         = $this->request->post('mobile');
        $identitycard   = $this->request->post('identitycard');

        if (!$username) {
            $this->error(__('账号必填'));
        }
        if (!$nickname) {
            $this->error(__('姓名必填'));
        }
        if(!$password){
            $this->error(__('密码必填'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号格式不对'));
        }
        if(!$wx){
            $this->error(__('微信号必填'));
        }
        if($this->auth->three_id){
            $this->error(__('添加的下级作单，下级没有佣金'));
        }
        $exd_arr =  [
            'nickname'  => $nickname,
            'wx'        => $wx,
            'spread'    => config('site.spread'),
            'parent_id' => $this->auth->id,
            'two_id'    => $this->auth->parent_id,
            'three_id'  => $this->auth->two_id,
            'identitycard' => $identitycard
        ];
        $ret = $this->auth->registerTwo($username, $password, '', $mobile,$exd_arr);
        if($ret){
            \app\common\model\User::where(['id'=>$exd_arr['parent_id']])->setInc('agency_num');
            $this->team_all_money_common($ret,$this->auth->commission_acquiesce,'inser');
            $this->success('添加成功');
        }
        $this->error($this->auth->getError());
    }


    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $username   姓名
     * @param string $mobile 手机号
     * @param string $truthname 真实姓名
     * @param string $zfb_account      支付宝账号
     */
    public function profile()
    {
        $user           = $this->auth->getUser();
        $nickname       = $this->request->post('nickname');
        $mobile         = $this->request->post('mobile');
        $truthname      = $this->request->post('truthname');
        $zfb_account    = $this->request->post('zfb_account');
        $wx    = $this->request->post('wx');
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('type',1)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('姓名已存在'));
            }
            $user->nickname = $nickname;
        }
        if ($mobile) {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('手机号格式不对'));
            }
            $exists = \app\common\model\User::where('mobile', $mobile)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('手机号已存在'));
            }
            $user->mobile = $mobile;
        }

        if($truthname){
            $user->truthname = $truthname;
        }

        if($zfb_account){
            $user->zfb_account = $zfb_account;
        }

        if($wx){
            $user->wx = $wx;
        }

        $user->save();
        $this->success();
    }


    //代理信息
    public function agedit()
    {
        $ids        = input('ids');
        if(!$ids){
            $this->error('缺少参数');
        }
        $ageditInfo = \app\common\model\User::where(['id'=>$ids,'parent_id'=>$this->auth->id])->field('id,username,mobile,nickname,bio,wx,identitycard,status')->find();
        if(!$ageditInfo){
            $this->error('代理信息不存在');
        }
        $this->success('ok',$ageditInfo);
    }

    /**
     * 修改代理信息
     */

    public function ageditprofile()
    {
        $ids        = input('ids');
        if(!$ids){
            $this->error('缺少参数');
        }
        $user           = \app\common\model\User::where(['id'=>$ids,'parent_id'=>$this->auth->id])->find();
        if(!$user){
            $this->error('代理不存在');
        }
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $password = $this->request->post('password');
        $identitycard   = $this->request->post('identitycard');
        $mobile   = $this->request->post('mobile');
        $status   = input('status');
        $wx       = $this->request->post('wx');
        if ($nickname) {
            $user->nickname = $nickname;
        }
        if ($username) {
            $user->username = $username;
        }
        if ($wx) {
            $user->wx = $wx;
        }
        if ($identitycard) {
            $user->identitycard = $identitycard;
        }
        if($status === ''){
            $user->status = 'hidden';
        }

        if($status === "1"){
            $user->status = 'normal';
        }
        if($password){
            $user->password = $this->auth->getEncryptPassword($password, $user['salt']);
        }
        if ($mobile) {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('手机号格式不对'));
            }
            if($user['mobile'] != $mobile){
                $exists = \app\common\model\User::where('mobile', $mobile)->find();
                if ($exists) {
                    $this->error(__('手机号已存在'));
                }
                $user->mobile = $mobile;
            }

        }
        $user->save();
        $this->success();
    }

    /**
     * 代理列表
     */
    public function ageditlist()
    {
        $where['parent_id'] = $this->auth->id;
        $username = input('username');
        $nickname = input('nickname');
        $mobile   = input('mobile');
        $phone    = input('phone');
        if($username){
            $where['username']  = ['like','%'.$username.'%'];
        }
        if($nickname){
            $where['nickname']  = ['like','%'.$nickname.'%'];
        }
        if($mobile){
            $where['mobile']  = $mobile;
        }
        if($phone){
            $where['mobile']  = $phone;
        }
        $where['type'] = 1;
        $data = \app\common\model\User::where($where)->field('id,username,nickname,audit,order_num,logintime,createtime,mobile,money')->order('id desc')->paginate(100);
        $arr = $data->toArray();
        foreach ($arr['data'] as $k=>&$v){
            $v['month_order'] = \app\common\model\Order::where(['user_id|parent_id'=>$v['id']])->whereTime('createtime', 'month')->count();
            $v['all_order'] = \app\common\model\Order::where(['user_id|parent_id'=>$v['id']])->count();
        }
        $superiors_mobile = '19903853566';
        $wx               = 'qunhong365';
        if($this->auth->parent_id){
            $userInfo = \app\common\model\User::where(['id'=>$this->auth->parent_id])->find();
            if($userInfo){
                $superiors_mobile = $userInfo['mobile'];
                $wx               = $userInfo['wx'];
            }

        }
        $arr['superiors_mobile']  = $superiors_mobile;
        $arr['superiors_wx']      = $wx;
        $arr['is_tan']            = false;
        $arr['commission_acquiesce'] = $this->auth->commission_acquiesce;
        $this->success('ok',$arr);
    }

    /**
     * 设置代理
     */

    public function addconfig(){
        $agent_id        = input('agent_id');
        if(!$agent_id){
            $this->error('缺少参数');
        }
        $money          = input('money');
        if(!$money || $money <= 0){
            $this->error('参数不合法');
        }
        $day            = input('day');
        $packages_id    = input('packages_id');
        $type           = input('type');
        $agentInfo      = \app\common\model\User::where(['id'=>$agent_id,'parent_id'=>$this->auth->id])->find();
        if(!$agentInfo){
            $this->error('代理不存在');
        }
        if($packages_id){
            $packagesInfo = Packages::where(['id'=>$packages_id])->find();
            if(!$packagesInfo){
                $this->error('产品不存在');
            }
            $config = new UserPackagesConfig();
            if($this->auth->three_id){
                $zhi_money = $config->where('user_id', $this->auth->three_id)->where(['packages_id'=>$packages_id])->value('money');
                if(!$zhi_money){
                    $zhi_money = $packagesInfo['rebate'];
                }
                $zhi_money -= $config->where('user_id', $this->auth->two_id)->where(['packages_id'=>$packages_id])->value('money');
                $zhi_money -= $config->where('user_id', $this->auth->parent_id)->where(['packages_id'=>$packages_id])->value('money');
            }elseif ($this->auth->two_id){
                $zhi_money = $config->where('user_id', $this->auth->two_id)->where(['packages_id'=>$packages_id])->value('money');
                if(!$zhi_money){
                    $zhi_money = $packagesInfo['rebate'];
                }
                $zhi_money -= $config->where('user_id', $this->auth->parent_id)->where(['packages_id'=>$packages_id])->value('money');
            }elseif ($this->auth->parent_id){
                $zhi_money = $config->where('user_id', $this->auth->parent_id)->where(['packages_id'=>$packages_id])->value('money');
                if(!$zhi_money){
                    $zhi_money = $packagesInfo['rebate'];
                }
            }
            if(!$this->auth->parent_id){
                $zhi_money = $config->where('user_id', $this->auth->id)->where(['packages_id'=>$packages_id])->value('money');
                if(!$zhi_money){
                    $zhi_money = $packagesInfo['rebate'];
                }
            }else{
                $zhi_money -= $config->where('user_id', $this->auth->id)->where(['packages_id'=>$packages_id])->value('money');
            }

            if($money >= $zhi_money){
                $this->error('佣金不能高于自己佣金');
            }
            $config = UserPackagesConfig::where(['user_id'=>$agent_id,'packages_id'=>$packages_id])->find();
            if($config){
                $config->money  = $money;
                $config->status = 1;
               $r = $config->save();
            }else{
                $inser['user_id']     = $agent_id;
                $inser['parent_id']   = $this->auth->id;
                $inser['packages_id'] = $packages_id;
                $inser['money']       = $money;
                $r = UserPackagesConfig::create($inser);
                soldout(2,$packages_id,$agent_id);
            }
            if(!$r){
                $this->error('操作失败');
            }
        }else{
            $this->team_all_money_common($agent_id,$money);
        }
        $this->success('操作成功');
    }


    public function batchconfig(){
        $packages_id    = input('packages_id');
        $money          = input('money');
        if(!$packages_id || !$money){
            $this->error('缺少参数');
        }
        $packagesInfo = Packages::where(['id'=>$packages_id])->find();
        if(!$packagesInfo){
            $this->error('产品不存在');
        }
        if($money > $packagesInfo['rebate']){
            $this->error('佣金不能高于自己佣金');
        }
        $usermodel = new \app\common\model\User();
        $user_all = $usermodel->where('parent_id', $this->auth->id)->orderBy('level', 'asc')->pluck('id');
        if($user_all){
            dump($user_all);
        }
        exit();
        $config = UserPackagesConfig::where(['parent_id'=>$this->auth->id,'packages_id'=>$packages_id])->select();
        if($config){
            $model   = new UserPackagesConfig();
            foreach ($config as $k=>$v){
                $count = $model->where(['id'=>$v['id']])->count();
                if($count){
                    $model->money  = $money;
                    $model->status = 1;
                }else{
                    $inser['money'] = $money;
                    $inser['packages_id'] = $packages_id;
                    $inser['parent_id']   = $this->auth->id;
                }
            }
        }
        UserPackagesConfig::where(['parent_id'=>$this->auth->id,'packages_id'=>$packages_id])->update(['money'=>$money]);
        $this->success('操作成功');
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 修改密码
     */
    public function uppwd()
    {
        $password          = $this->request->post("password");//原密码
        $newpassword     = $this->request->post("newpassword");//新密码
        $newpassword_tow = $this->request->post("newpassword_tow");//确认密码

        if($this->auth->getEncryptPassword($password, $this->auth->salt) != $this->auth->password){
            $this->error('登录密码错误');
        }
        if($newpassword != $newpassword_tow){
            $this->error('两次密码不一致');
        }
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('修改成功'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 生成二维码
     */

    public function qrcode(){
        $ids = input('ids');
        if(!$ids){
            $this->error('缺少参数');
        }
        $url      = 'https://'.$_SERVER['HTTP_HOST'].'/qing/#/pages/order/order_details?id='.$ids.'&agid='.$this->auth->id;
        $image    = trim(shengcode($url,'goods-'.$ids.'-'.$this->auth->id),'.');
        $this->success('ok',$image);
    }

    public function team_all_money(){
        $money = input('money');
        $user           = $this->auth->getUser();
        $user->commission_acquiesce = $money;
        $user->save();
        $this->team_all_money_common(0,$money);
    }

    /**
     * @menu 所有下级统一佣金
     * @Author:男人的坏
     * @Date:2024-05-12 16:12
     */
    public function team_all_money_common($user_id,$money,$status='up'){
        $where['parent_id'] = $this->auth->id;
        if($user_id){
            $where['id'] = $user_id;
        }
        $data = \app\common\model\User::where($where)->field('id')->column('id');
        if($data){
           $packagesData =  \app\admin\model\Packages::where(['status'=>1])->whereIn('type','1,2')->field('id,day,rebate')->select();
           if($packagesData){
               $configModel       = new UserPackagesConfig();
               foreach ($packagesData as $k=>$v){
                   $config = new UserPackagesConfig();
                   $packages_where['packages_id'] = $v['id'];
                   if($this->auth->three_id){
                       $zhi_money = $config->where('user_id', $this->auth->three_id)->where($packages_where)->value('money');
                       if(!$zhi_money){
                           $zhi_money = $v['rebate'];
                       }
                       $zhi_money -= $config->where('user_id', $this->auth->two_id)->where($packages_where)->value('money');
                       $zhi_money -= $config->where('user_id', $this->auth->parent_id)->where($packages_where)->value('money');
                   }elseif ($this->auth->two_id){
                       $zhi_money = $config->where('user_id', $this->auth->two_id)->where($packages_where)->value('money');
                       if(!$zhi_money){
                           $zhi_money = $v['rebate'];
                       }
                       $zhi_money -= $config->where('user_id', $this->auth->parent_id)->where($packages_where)->value('money');
                   }elseif ($this->auth->parent_id){
                       $zhi_money = $config->where('user_id', $this->auth->parent_id)->where($packages_where)->value('money');
                       if(!$zhi_money){
                           $zhi_money = $v['rebate'];
                       }
                   }
                   if(!$this->auth->parent_id){
                       $zhi_money = $config->where('user_id', $this->auth->id)->where($packages_where)->value('money');
                       if(!$zhi_money){
                           $zhi_money = $v['rebate'];
                       }
                   }else{
                       $zhi_money -= $config->where('user_id', $this->auth->id)->where($packages_where)->value('money');
                   }

                   if($money < $zhi_money){
                       foreach ($data as $kk=>$vv){
                           $configInfo = $configModel->where(['user_id'=>$vv,'packages_id'=>$v['id']])->find();
                           if($user_id && $status =='up'){
                               if($configInfo){
                                   $configInfo->money = $money;
                                   $configInfo->save();
                               }
                           }else{
                               if(!$configInfo){
                                       $configModel->create([
                                       'parent_id'   => $this->auth->id,
                                       'packages_id' => $v['id'],
                                       'user_id'     => $vv,
                                       'money'       => $money
                                   ]);
                               }
                               soldout(2,$v['id'],$vv);
                           }
                       }
                   }
               }
           }
        }
        $this->success('ok');
    }

    /**
     * 推广二维码
     */

    public function extendqrcode()
    {
        if(!$this->auth->invitation_code){
            $user          = $this->auth->getUser();
            $this->auth->invitation_code = Random::alnum(8);
            $user->invitation_code = $this->auth->invitation_code;
            $user->save();
        }
        $url            = 'https://'.$_SERVER['HTTP_HOST'].'/qing/#/pages/signIn/register?share_code='.$this->auth->invitation_code;
        $image          = trim(shengcode($url, 'user-'.$this->auth->id, 'userqrcode'), '.');
        $user_qrcode_bg = db('config')->where(['name' => 'user_qrcode_bg'])->value('value');
        $this->success('ok', ['qrcode' => cdnurl($image, true,2), 'bg' => $user_qrcode_bg, 'share_url' => $url]);
    }
}
